package com.amikomgamedev.panjatpinang.states;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.camera.hud.HUD;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.ui.activity.SimpleBaseGameActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.view.KeyEvent;

import com.amikomgamedev.panjatpinang.Data;
import com.amikomgamedev.panjatpinang.Define;
import com.amikomgamedev.panjatpinang.Utils;
import com.amikomgamedev.panjatpinang.database.ScoreDbHelper;
import com.amikomgamedev.panjatpinang.database.ScoreSVC;

/*
 * AndEngineGamePanjatPinang
 * State_Leaderboard.java
 * Pratama Wijaya
 * set.mnemonix@gmail.com
 * 2:18:30 PM , Aug 5, 2012
 */

public class State_Leaderboard extends SimpleBaseGameActivity implements
		Define, Data {
	private Camera	mCamera;
	private Scene	mScene;

	private BitmapTextureAtlas	texBg, texPaper, texPiala, texFont;
	private ITextureRegion		treBg, trePaper, trePiala, treFont;
	private Sprite				sprBg, sprPaper, sprPiala, sprFont;

	private BitmapTextureAtlas	texFontSmall;
	private static Font			fontSmall;
	private Text				offLineHighScore, namaOffline, scoreOffline;
	private Text				txtNoConnection, namaOnline, scoreOnline;
	private Text[]				onlineNama	= new Text[10];
	private Text[]				onlineScore	= new Text[10];
	private ScoreDbHelper		scoreDb;
	private ScoreSVC			scoreSvc;
	private HUD					hud;

	private AlertDialog.Builder	alert;

	@Override
	public EngineOptions onCreateEngineOptions() {
		// TODO Auto-generated method stub
		mCamera = new Camera(0, 0, GAME_SCREEN_WIDTH, GAME_SCREEN_HEIGHT);
		EngineOptions en = new EngineOptions(true,
				ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(
						GAME_SCREEN_WIDTH, GAME_SCREEN_HEIGHT), mCamera);
		return en;
	}

	@Override
	protected void onCreateResources() {
		// TODO Auto-generated method stub

		texBg = new BitmapTextureAtlas(this.getTextureManager(), 512, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		texPaper = new BitmapTextureAtlas(this.getTextureManager(), 512, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		texPiala = new BitmapTextureAtlas(this.getTextureManager(), 256, 128,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		texFont = new BitmapTextureAtlas(this.getTextureManager(), 256, 64,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);

		treFont = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				texFont, this.getAssets(), IMG_FONT_LEADERBOARD, 0, 0);
		treBg = BitmapTextureAtlasTextureRegionFactory.createFromAsset(texBg,
				this.getAssets(), IMG_LEADERBOARD_BG, 0, 0);
		trePaper = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				texPaper, this.getAssets(), IMG_LEADERBOARD_PAPER, 0, 0);
		trePiala = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				texPiala, this.getAssets(), IMG_LEADERBOARD_PIALA, 0, 0);

		texFontSmall = new BitmapTextureAtlas(this.getTextureManager(), 256,
				256, TextureOptions.BILINEAR);
		fontSmall = FontFactory.createFromAsset(this.getFontManager(),
				texFontSmall, this.getAssets(), FONT_STYLE, FONT_SIZE_SMALL,
				true, Color.BLACK);

		texFont.load();
		texBg.load();
		texPaper.load();
		texPiala.load();
		fontSmall.load();

		hud = new HUD();
		mCamera.setHUD(hud);

		alert = new AlertDialog.Builder(this);

	}

	private void noConnection() {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				alert.setMessage("No Internet Connection")
						.setCancelable(false)
						.setNegativeButton("Ok",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub

									}
								});
				alert.show();
			}
		});

	}

	@Override
	protected Scene onCreateScene() {
		// TODO Auto-generated method stub
		mScene = new Scene();
		sprBg = new Sprite(0, 0, treBg, mEngine.getVertexBufferObjectManager());
		sprPaper = new Sprite(0, 0, trePaper,
				mEngine.getVertexBufferObjectManager());
		sprPiala = new Sprite(Utils.getRatioW(180), 0, trePiala,
				mEngine.getVertexBufferObjectManager());
		sprFont = new Sprite(0, 0, treFont,
				mEngine.getVertexBufferObjectManager());

		mScene.attachChild(sprBg);
		mScene.getLastChild().attachChild(sprFont);
		mScene.getLastChild().attachChild(sprPiala);
		mScene.getLastChild().attachChild(sprPaper);

		// score ONLINE

		txtNoConnection = new Text(0, 0, fontSmall, "No Connection",
				mEngine.getVertexBufferObjectManager());

		namaOnline = new Text(Utils.getRatioW(72), Utils.getRatioH(90),
				fontSmall, "Nama", mEngine.getVertexBufferObjectManager());
		scoreOnline = new Text(Utils.getRatioW(210), Utils.getRatioH(90),
				fontSmall, "Score", mEngine.getVertexBufferObjectManager());

		hud.attachChild(namaOnline);
		hud.attachChild(scoreOnline);

		scoreSvc = new ScoreSVC();
		String hasil[][] = scoreSvc.getTopTen();

		if (hasil != null) {
			// jika connect
			for (int i = 0; i < hasil.length; i++) {
				onlineNama[i] = new Text(0, 0, fontSmall, "aaaaaaaaaaaaaaa",
						mEngine.getVertexBufferObjectManager());
				onlineNama[i].setPosition(Utils.getRatioW(72),
						Utils.getRatioH(120) + (i * Utils.getRatioH(25)));

				onlineScore[i] = new Text(0, 0, fontSmall, "0000000000000",
						mEngine.getVertexBufferObjectManager());
				onlineScore[i].setPosition(Utils.getRatioW(210),
						Utils.getRatioH(120) + (i * Utils.getRatioH(25)));
				// attach
				hud.attachChild(onlineNama[i]);
				hud.attachChild(onlineScore[i]);

				// end attach
				String nama = hasil[i][0];
				// int score = Integer.parseInt(hasil[i][1]);
				float score = Float.parseFloat(hasil[i][1]);

				onlineNama[i].setText(nama);
				onlineScore[i].setText("" + String.format("%.02f", score));
			}

		} else {
			// jika tidak
			noConnection();

			txtNoConnection.setPosition((GAME_SCREEN_WIDTH >> 1)
					- txtNoConnection.getWidth() / 2, GAME_SCREEN_HEIGHT >> 1);

			txtNoConnection.setColor(org.andengine.util.color.Color.BLACK);
			mScene.getLastChild().attachChild(txtNoConnection);
		}

		scoreDb = new ScoreDbHelper(this);
		scoreDb.CreateTable();

		float num = Float.parseFloat(scoreDb.getLatestScore());

		offLineHighScore = new Text(0, 0, fontSmall, "Offline High Score",
				mEngine.getVertexBufferObjectManager());
		offLineHighScore.setPosition((GAME_RATIO_SCREEN_WIDTH >> 1)
				- offLineHighScore.getWidth() / 2, Utils.getRatioH(410));

		namaOffline = new Text(0, 0, fontSmall, scoreDb.getLatestName(),
				mEngine.getVertexBufferObjectManager());
		namaOffline.setPosition(Utils.getRatioW(80), offLineHighScore.getY()
				+ offLineHighScore.getHeight() + 10);

		scoreOffline = new Text(0, 0, fontSmall, ""
				+ String.format("%.02f", num),
				mEngine.getVertexBufferObjectManager());
		scoreOffline.setPosition(namaOffline.getX() + namaOffline.getWidth()
				+ Utils.getRatioW(100), namaOffline.getY());

		mScene.getLastChild().attachChild(offLineHighScore);
		mScene.getLastChild().attachChild(namaOffline);
		mScene.getLastChild().attachChild(scoreOffline);

		return mScene;
	}

	@Override
	public boolean onKeyDown(final int keyCode, final KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent menu = new Intent(State_Leaderboard.this,
					State_MainMenu.class);
			startActivity(menu);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

}
